using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JoyfulHomeJourney.BackEnd.Infrastructure.Atrributes;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Requests.Objects;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses.Objects;
using JoyfulHomeJourney.BackEnd.Infrastructure.EFCore;
using JoyfulHomeJourney.BackEnd.Server.EFCore;
using JoyfulHomeJourney.BackEnd.Server.Instances.Extends.Requests;
using JoyfulHomeJourney.BackEnd.Server.Instances.Extends.Responses;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace JoyfulHomeJourney.BackEnd.Server.Instances
{
/// <summary>
/// 一个类包含了服务类所需的所有仓库表的实例，仅提供给该服务类使用，请将所有服务类所需的仓库表的实例都放在该类中。
/// 仓库表的实例指提供了操作数据库指定表的所有方法的对象
/// </summary>
	internal class CustomerOrdersEF
	{
		public CustomerOrdersEF(DbContext dbContext)
		{
			customerOrdersServerEF = new CustomerOrdersServerEF(dbContext);
            sysCarShopsServerEF = new SysCarShopsServerEF(dbContext);
            offlineOrdersServerEF = new OfflineOrdersServerEF(dbContext);
        }
		public CustomerOrdersServerEF customerOrdersServerEF { get; set; }
        public SysCarShopsServerEF sysCarShopsServerEF { get; set; }
        public OfflineOrdersServerEF offlineOrdersServerEF { get; set; }
    }
	[InjectClass]
	public class CustomerOrdersServer : ICustomerOrdersServer
	{
		private readonly CustomerOrdersEF _customerOrdersEF;//包含所有所需仓库表实现的对象
		// 请不要修改该构造方法,也无需添加属性，而应该在上面的EF类中添加属性和构造函数赋值语句
		public CustomerOrdersServer(DbContext dbContext)
		{
			_customerOrdersEF = new CustomerOrdersEF(dbContext);
		}
		public async Task<ResponseApiDto> AddAsync(RequestCustomerOrdersDto dto)
		{
			return ResponseApiDto.Create(await _customerOrdersEF.customerOrdersServerEF.AddAsync(dto.ToCreateEntity()));
		}
		public async Task<ResponseApiDto> DeleteAsync(RequestCustomerOrdersDto dto)
		{
			return ResponseApiDto.Create(await _customerOrdersEF.customerOrdersServerEF.DeleteAsync(dto.ToDeleteEntity()));
		}
		public async Task<ResponseApiDto> UpdateAsync(RequestCustomerOrdersDto dto)
		{
			return ResponseApiDto.Create(await _customerOrdersEF.customerOrdersServerEF.UpdateAllProperNotNullAsync(dto.ToUpdateEntity()));
		}
		public async Task<ResponseApiDto> PaginationAsync(int page, int limit)
		{
			int total = 0;
			List<ResponseCustomerOrdersDto> data = new List<ResponseCustomerOrdersDto>();
			List<CustomerOrders> customerOrderss = await _customerOrdersEF.customerOrdersServerEF.Pagination1(d=>true,false, d => d.CoCreateAt, out total, page, limit).ToListAsync();
			foreach (var customerOrders in customerOrderss)
			{
				data.Add(customerOrders.ToResponseDto());
			}
			return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { total=total,data=data});
		}
        /// <summary>
        /// 查询统计和订单
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseApiDto> Get_orders(string timeType,string cid)
        {
            string csid = await _customerOrdersEF.sysCarShopsServerEF.Query(d => d.CsAccount == cid).Select(d => d.CsId).FirstOrDefaultAsync();
			List<object> data = new List<object>();
            List<object> data2 = new List<object>();
            if (timeType == "day") {
                DateTime todayStart = DateTime.Today; // 当天的开始时间（00:00:00）
                DateTime todayEnd = DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59); // 当天的结束时间（23:59:59）
                //线上
                var orders = await _customerOrdersEF.customerOrdersServerEF.Query(d => d.CoCarShopId == csid && (todayStart <= d.CoCreateAt && todayEnd >= d.CoCreateAt)).ToListAsync();
                int count = orders.Count;
                decimal totalAmount = orders.Sum(d => d.CoPayCount ?? 0);
                decimal avgAmount = count == 0 ? 0 : totalAmount / count;
                var ip = await _customerOrdersEF.customerOrdersServerEF.Query(d => d.CoCarShopId == csid && (todayStart <= d.CoCreateAt && todayEnd >= d.CoCreateAt)).ToListAsync();
                ip.ForEach(d => data2.Add(new
                {
                    paymd = d.CoPayCount,
                    status = d.CoStatus,
                    create = d.CoCreateAt,
                    id = d.CoId,
                }));
                //线下
                var off = await _customerOrdersEF.offlineOrdersServerEF.Query(d => d.OoCarShopId == csid && (todayStart <= d.OoCreateAt && todayEnd >= d.OoCreateAt)).ToListAsync();
                int count2 = off.Count;
                decimal totalAmount2 = off.Sum(d => d.OoPayCount ?? 0);
                decimal avgAmount2 = count2 == 0 ? 0 : totalAmount2 / count2;
                var ip2 = await _customerOrdersEF.offlineOrdersServerEF.Query(d => d.OoCarShopId == csid && (todayStart <= d.OoCreateAt && todayEnd >= d.OoCreateAt)).ToListAsync();
                ip2.ForEach(d => data2.Add(new
                {
                    paymd = d.OoPayCount,
                    status = d.OoStatus,
                    create = d.OoCreateAt,
                    id = d.OoId,
                }));

                data.Add(new
                {
                    totalOrders = count+ count2,
                    totalAmount = totalAmount+ totalAmount2,
                    avgAmount = avgAmount+ avgAmount2,
                    orderList = data2,
                });
            }
            if (timeType == "month")
            {
                DateTime oneMonthAgo = DateTime.Now.AddMonths(-1);
                DateTime todayEnd = DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59); // 当天的结束时间（23:59:59）
                //线上
                var orders = await _customerOrdersEF.customerOrdersServerEF.Query(d => d.CoCarShopId == csid && (oneMonthAgo <= d.CoCreateAt && todayEnd >= d.CoCreateAt)).ToListAsync();
                int count = orders.Count;
                decimal totalAmount = orders.Sum(d => d.CoPayCount ?? 0);
                decimal avgAmount = count == 0 ? 0 : totalAmount / count;
                var ip = await _customerOrdersEF.customerOrdersServerEF.Query(d => d.CoCarShopId == csid && (oneMonthAgo <= d.CoCreateAt && todayEnd >= d.CoCreateAt)).ToListAsync();
                ip.ForEach(d => data2.Add(new
                {
                    paymd = d.CoPayCount,
                    status = d.CoStatus,
                    create = d.CoCreateAt,
                    id = d.CoId,
                }));
                //线下
                var off = await _customerOrdersEF.offlineOrdersServerEF.Query(d => d.OoCarShopId == csid && (oneMonthAgo <= d.OoCreateAt && todayEnd >= d.OoCreateAt)).ToListAsync();
                int count2 = off.Count;
                decimal totalAmount2 = off.Sum(d => d.OoPayCount ?? 0);
                decimal avgAmount2 = count2 == 0 ? 0 : totalAmount2 / count2;
                var ip2 = await _customerOrdersEF.offlineOrdersServerEF.Query(d => d.OoCarShopId == csid && (oneMonthAgo <= d.OoCreateAt && todayEnd >= d.OoCreateAt)).ToListAsync();
                ip2.ForEach(d => data2.Add(new
                {
                    paymd = d.OoPayCount,
                    status = d.OoStatus,
                    create = d.OoCreateAt,
                    id = d.OoId,
                }));

                data.Add(new
                {
                    totalOrders = count + count2,
                    totalAmount = totalAmount + totalAmount2,
                    avgAmount = avgAmount + avgAmount2,
                    orderList = data2,
                });
            }
            if (timeType == "year")
            {
                DateTime oneYearAgo = DateTime.Now.AddYears(-1);
                DateTime todayEnd = DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59); // 当天的结束时间（23:59:59）
                //线上
                var orders = await _customerOrdersEF.customerOrdersServerEF.Query(d => d.CoCarShopId == csid && (oneYearAgo <= d.CoCreateAt && todayEnd >= d.CoCreateAt)).ToListAsync();
                int count = orders.Count;
                decimal totalAmount = orders.Sum(d => d.CoPayCount ?? 0);
                decimal avgAmount = count == 0 ? 0 : totalAmount / count;
                var ip = await _customerOrdersEF.customerOrdersServerEF.Query(d => d.CoCarShopId == csid && (oneYearAgo <= d.CoCreateAt && todayEnd >= d.CoCreateAt)).ToListAsync();
                ip.ForEach(d => data2.Add(new
                {
                    paymd = d.CoPayCount,
                    status = d.CoStatus,
                    create = d.CoCreateAt,
                    id = d.CoId,
                }));
                //线下
                var off = await _customerOrdersEF.offlineOrdersServerEF.Query(d => d.OoCarShopId == csid && (oneYearAgo <= d.OoCreateAt && todayEnd >= d.OoCreateAt)).ToListAsync();
                int count2 = off.Count;
                decimal totalAmount2 = off.Sum(d => d.OoPayCount ?? 0);
                decimal avgAmount2 = count2 == 0 ? 0 : totalAmount2 / count2;
                var ip2 = await _customerOrdersEF.offlineOrdersServerEF.Query(d => d.OoCarShopId == csid && (oneYearAgo <= d.OoCreateAt && todayEnd >= d.OoCreateAt)).ToListAsync();
                ip2.ForEach(d => data2.Add(new
                {
                    paymd = d.OoPayCount,
                    status = d.OoStatus,
                    create = d.OoCreateAt,
                    id = d.OoId,
                }));

                data.Add(new
                {
                    totalOrders = count + count2,
                    totalAmount = totalAmount + totalAmount2,
                    avgAmount = avgAmount + avgAmount2,
                    orderList = data2,
                });
            }
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto {  data = data });
        }
    }
}
